package com.wxw.BaseLibrary.net;

import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.SyncHttpClient;
import com.loopj.android.http.TextHttpResponseHandler;
import com.wxw.BaseLibrary.http.RequestCmd;
import com.wxw.BaseLibrary.http.RequestManager;
import com.wxw.BaseLibrary.http.RequestMessage;
import com.wxw.BaseLibrary.http.soap.SoapListener;
import com.wxw.BaseLibrary.net.bean.PS_Message;
import com.wxw.BaseLibrary.net.listener.IMessageContainer;
import com.wxw.BaseLibrary.net.listener.PushMessageQueryListener;
import com.wxw.BaseLibrary.tool.AES;
import com.wxw.BaseLibrary.tool.SystemTool;
import org.apache.http.Header;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class MessageContainer implements IMessageContainer {
    private static MessageContainer _container;
    private CopyOnWriteArrayList<PS_Message> messages = new CopyOnWriteArrayList<>();
    private PushMessageQueryListener pushMessageQueryListener;
    
    private MessageContainer() {
        
    }

    public static MessageContainer getInstance() {
        if (_container == null) {
            _container = new MessageContainer();
        }
        return _container;
    }

    @Override
    public void push(PS_Message message) {
        messages.add(message);
    }

    @Override
    public PS_Message pop() {
        return messages.remove(0);
    }

    @Override
    public int count() {
        return messages.size();
    }

    @Override
    public void queryPushMessage(String app_ak, String userid, PushMessageQueryListener listener) {
        this.pushMessageQueryListener = listener;
        try {
            RequestCmd cmd = new RequestCmd();
            cmd.UID = app_ak;
            cmd.UserID = userid;
            String ss = new Gson().toJson(cmd);
//            ss = AES.encode(SystemTool.string2Unicode(ss));
//            SyncHttpClient client = new SyncHttpClient();
//            client.setResponseTimeout(1800);

            RequestManager.getRequestManager().addSoapListener("querymessage", new SoapListener() {
                @Override
                public void onStart(int what) {

                }

                @Override
                public void onFinish(int what) {

                }

                @Override
                public void onSucceed(int what, Object o) {
                    List<PS_Message> messageList = null;
                    RequestMessage message = (RequestMessage)o;
                    try {
                        RequestCmd cmd = AsyncClient.getInstance().getGson().fromJson(message.ResponseContent, RequestCmd.class);
                        messageList = AsyncClient.getInstance().getGson().fromJson(cmd.Result, new TypeToken<List<PS_Message>>(){}.getType());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    doEvent(messageList, "");
                }

                @Override
                public void onProgress(long bytesWritten, long totalSize) {

                }

                @Override
                public void onFailed(int what, String url, Exception ex, int StatusCode, long networkMillis) {
                    doEvent(null, ex.getMessage());
                }
            });
            RequestMessage.insertRequestMessage("queryMessage", ss, "PushSysService",
                    "QueryMessage", "s", "querymessage");

//            RequestParams params = new RequestParams();
//            params.put("s", ss);
//            client.post("http://218.13.183.14:29880/axis2/services/PushSysService/QueryMessage",
//                    params,
//                    textHttpResponseHandler);
        } catch (Exception e) {

        }
    }

    private void doEvent(List<PS_Message> messageList, String msg) {
        if (pushMessageQueryListener != null) {
            pushMessageQueryListener.onReceived(this, messageList, msg);
        }
        if (messageList != null && messageList.size() > 0) {
            messages.clear();
            messages.addAll(messageList);
        }
    }

//    private TextHttpResponseHandler textHttpResponseHandler = new TextHttpResponseHandler() {
//        @Override
//        public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
//            if (s == null) {
//                s = throwable.getMessage();
//                if (s.startsWith("Connect") && s.endsWith("timed out")) {
//                    s = "连接服务器超时，服务器当前无法连接！(" + s + ")";
//                }
//            }
//            doEvent(null, s);
//        }
//
//        @Override
//        public void onSuccess(int i, Header[] headers, String s) {
//            String msg = s;
//            List<PS_Message> messageList = null;
//            try {
//                int start = s.indexOf("<ns:return>") + 11;
//                int end = s.indexOf("</ns:return>");
//                msg = s.substring(start, end);
//                messageList = AsyncClient.getInstance().getGson().fromJson(msg, new TypeToken<List<PS_Message>>(){}.getType());
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            doEvent(messageList, "");
//        }
//    };
}